<?php
include_once('./simple_html_dom.php');

// Make MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("otafood") or die(mysql_error());


// Setting the default value of not available for every item in the database
mysql_query('UPDATE foodlist SET available_today = ' . mysql_real_escape_string('0'));


// Service from where we get today's available items
$URL = "http://aaltolunch.fi/campus.jsp?c=TKK";
$html = file_get_html($URL);


// Selectively make items available or insert new items if already not in the database
foreach($html->find('tr') as $row) {
	$class = $row->getAttribute('class');

	if ($class == 'restaurantName') {
		$restname = $row->find('td',0)->find('label',0)->innertext;
		if ($restname == null) {
			$restname = $row->find('td',0)->innertext;
		}
	}
	if ($class == 'tableRow') {
		$foodname = $row->find('td',0)->innertext;
		
		// Query formulation to check if the food + restaurant combination already exists
		$query = sprintf("SELECT food, restaurant FROM foodlist WHERE food='%s' AND restaurant='%s'",
    		mysql_real_escape_string($foodname),
    		mysql_real_escape_string($restname));
    	
    	// Perform Query
		$result = mysql_query($query);
		
		if(!$result)
			echo "error<br/>";
		else {
			$row = mysql_fetch_row($result);
			if($row[0] === null) {
				// No existing records of food + restaurant combination found
				echo "not found<br/>";
				mysql_insert('foodlist', array(
					'food' => $foodname,
					'restaurant' => $restname,
					'rating' => 0.0,
					'available_today' => 1
				));
			}
			else {
				// Records of food + restaurant combination exists; we just have to update it
				echo $restname . "found<br/>";
				$query = sprintf("UPDATE foodlist SET available_today='%s' WHERE food='%s' AND restaurant='%s'",
					mysql_real_escape_string('1'),
					mysql_real_escape_string($foodname),
					mysql_real_escape_string($restname));
			
				// Perform Query
				$result = mysql_query($query);
			}
		}


	}
}


// Insert function for general mysql INSERT
function mysql_insert($table, $inserts) {
	echo "mysql_insert<br/>";
    $values = array_map('mysql_real_escape_string', array_values($inserts));
    $keys = array_keys($inserts);
       
    return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}

?>
